<template>
	<up-skeleton rows="3" :loading="loading || !loaded">
		<view class="page">
			<view class="info">
				<icon :type="type" size="68"></icon>
				<text class="msg">{{ msg }}</text>
			</view>

			<view style="width: 60%; margin: 0 auto;">
				<button type="primary" @click="goHome">回到首页</button>
			</view>
		</view>
	</up-skeleton>
</template>

<script setup>
	import useAppStore from '@/store/app.js'
	import {
		getQueryString,
	} from '@/common/utils/index.js'
	import api from '@/api/app.js'

	const appStore = useAppStore()
	const agentIdKey = 'id'
	const tKey = 't'
	const id = ref('')
	const loaded = ref(false)
	const timestamp = ref(0)
	const loading = ref(true)
	const type = ref('success')
	const msg = ref('')

	function agentBind() {
		loading.value = true;
		api.bindAgent({
			admin_id: id.value
		}, {
			showLoading: true,
		}).then(() => {
			type.value = 'success'
			msg.value = '绑定成功，点击返回首页'
			appStore.getUserInfo()
		}).catch((res) => {
			type.value = 'warn'
			msg.value = res.msg || '绑定失败'
		}).finally(() => {
			loading.value = false;
		})
	}

	function goHome() {
		uni.reLaunch({
			url: '/pages/index/index',
		})
	}


	onLoad((query) => {
		if (query[agentIdKey]) {
			id.value = query[agentIdKey]
			timestamp.value = query[tKey]
		} else if (query.q && query.q.includes(agentIdKey)) {
			id.value = getQueryString(query.q, agentIdKey)
			timestamp.value = getQueryString(query.q, tKey)
		}
		// 如果参数中获取的时间戳对比当前时间戳超过5分钟，则不绑定
		if (timestamp.value && Date.now() - timestamp.value > 5 * 60 * 1000) {
			type.value = 'warn'
			msg.value = '二维码已过期'
			loading.value = false
			return
		}
		if (appStore.isLogin) {
			loaded.value = true
			agentBind()
		} else {
			appStore.login().then(() => {
				loaded.value = true
				agentBind()
			})
		}
	})
</script>

<style lang="scss" scoped>
	.page {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		height: 100vh;
		padding: 36px 0 60px;
		background-color: #fff;
	}

	.info {
		display: flex;
		flex-direction: column;
		align-items: center;

		.msg {
			font-size: 18px;
			color: #181818;
		}

		icon {
			margin-bottom: 16px;
		}
	}
</style>